package org.cainiao.basic.concurrent.juc.aqs.cyclicbarrier;

import org.cainiao.util.Util;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

/**
 * <br />
 * <p>
 * Author: Cai Niao(wdhlzd@163.com)<br />
 */
public class CyclicBarrierTest {

    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(2, () -> {
            try {
                Util.logLn("await > sleep");
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            Util.logLn("await > end");
        });

        Util.logLn(" --- start");
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    Util.logLn("before await");
                    Util.logLn("await return %d", barrier.await());
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
                Util.logLn("end");
            }, String.format("Thread %d", i)).start();
        }
    }
}
